package com.zynn.common.core.base;

import com.alibaba.fastjson.JSONObject;
import com.zynn.common.core.dto.LoginAndRegisterResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import redis.clients.jedis.JedisCluster;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Optional;

/**
 * @author jerry-liqi
 *
 * 基础的Controller
 *
 */
@Slf4j
public class BaseController {

    @Autowired
    private JedisCluster jedisCluster;

    private static ThreadLocal<ServletRequest> currentRequest = new ThreadLocal<ServletRequest>();

    @ModelAttribute
    protected void initReqAndRep(HttpServletRequest request, HttpServletResponse response) {
        currentRequest.set(request);
    }

    protected HttpServletRequest request() {
        return (HttpServletRequest) currentRequest.get();
    }

    /**
     * 打印请求的信息
     */
    protected void printRequestInfo() {
        StringBuilder paramBuilder = new StringBuilder();
        String requestInfo = "requestUrl:s%\nrequestParam:s%\nuserInfoKey:s%";
        //获取所有的请求参数
        Enumeration<String> paraNames = request().getParameterNames();
        while (paraNames.hasMoreElements()) {
            String thisName = paraNames.nextElement();
            String thisValue = request().getParameter(thisName);
            paramBuilder.append(thisName).append("=").append(thisValue).append("&");
        }
        String param = StringUtils.substringBeforeLast(paramBuilder.toString(), "&");
        //获取header中的用户信息
        String userInfoKey = request().getHeader("USER_INFO_KEY");
        log.error(String.format(requestInfo, request().getRequestURI(), param, userInfoKey));
    }

    /**
     * 获取当前登录的用户ID
     *
     * @return Long UserId
     */
    protected Long getCurrentUserId() {
        String userId = request().getHeader("loginUserId");
        if (StringUtils.isEmpty(userId)) {
            //做一步兼容性 可兼容1.0
            userId = request().getParameter("userId");

        }
        if (StringUtils.isEmpty(userId)) {
            //跳过Zuul接口,未放置loginUserId,重新解析USER_INFO_KEY获取userId
            String md5Str = request().getHeader("USER_INFO_KEY");
            if (StringUtils.isEmpty(md5Str)) {
                return null;
            }
            String s = jedisCluster.get(md5Str);
            if (StringUtils.isEmpty(s)) {
                return null;
            }
            LoginAndRegisterResultDTO user = Optional.ofNullable(JSONObject.parseObject(s, LoginAndRegisterResultDTO.class))
                    .orElse(new LoginAndRegisterResultDTO());
            return user.getUserid();
        }
        return Long.parseLong(userId);

    }
}
